package fr.insee.solr.service.impl;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import fr.insee.solr.model.annotation.CachAnnotation;
import fr.insee.solr.model.annotation.SolrField;
import fr.insee.solr.model.annotation.SolrFields;
import fr.insee.solr.service.SolrCreateService;
import fr.insee.solr.service.state.StateFactory;

public class SolrBeanIndexer<U> implements SolrCreateService<U>{

	public Map<String,Object> getFieldsValue(U o) throws SolrInseeException {
		Map<String,Object> fieldsValue = new HashMap<>();
		Field[] simplefield = CachAnnotation.getSolrfield(o.getClass());
		Field[] arrayfield = CachAnnotation.getSolrfields(o.getClass());
		
		for(Field f : simplefield){
			SolrField a = f.getAnnotation(SolrField.class);
			Object value = this.getSingle(f,a,o);
			
			if(value != null) fieldsValue.put(a.fieldName(), value);
		}
		
		for(Field f : arrayfield){
			SolrFields a = f.getAnnotation(SolrFields.class);
			for(SolrField sf : a.fields()){
				Object value = this.getSingle(f,sf,o);
				
				if(value != null) fieldsValue.put(sf.fieldName(), value);
			}
		}
		
		return fieldsValue;
	}

	private Object getSolrFieldValue(Field f,SolrField a,Object o) throws SolrInseeException{
		return StateFactory.getState(a).getValue(f, a, o);
	}
	
	private Object getSingle(Field f,SolrField a,Object o) throws SolrInseeException{
		Object value = null;
		if(a.index()){
			value = this.getSolrFieldValue(f,a,o);
		}
		
		return value;
	}

}
